package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import me.chanjar.weixin.common.util.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取声音的上次跳出时间
     * @param trackId
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (userListenProcess != null) {
            return userListenProcess.getBreakSecond();
        }
        return new BigDecimal(0);
    }

    /**
     * 更新播放进度
     * @param userId
     * @param userListenProcessVo
     */
    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
        BigDecimal breakSecond = userListenProcessVo.getBreakSecond();
        Long albumId = userListenProcessVo.getAlbumId();
        Long trackId = userListenProcessVo.getTrackId();
        //更新播放信息
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (userListenProcess != null) {
            userListenProcess.setBreakSecond(breakSecond);
            userListenProcess.setUpdateTime(new Date());
        }else {
            userListenProcess = new UserListenProcess();
            userListenProcess.setUserId(userId);
            userListenProcess.setAlbumId(albumId);
            userListenProcess.setTrackId(trackId);
            userListenProcess.setBreakSecond(breakSecond);
            userListenProcess.setIsShow(1);
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
        }
        mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));

        //增加统计数据
        //创建的当天的分布式锁
        String redisClockName = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + ":" + trackId;
        long ttl = DateUtil.endOfDay(new Date()).getTime() - new Date().getTime();
        Boolean isClock = redisTemplate.opsForValue().setIfAbsent(redisClockName, 1, ttl, TimeUnit.MILLISECONDS);
        if (isClock){
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setBusinessNo(IdUtil.getSnowflakeNextIdStr());
            trackStatMqVo.setAlbumId(albumId);
            trackStatMqVo.setTrackId(trackId);
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
        }
    }

    /**
     * 获取用户最近一次播放记录
     * @param userId
     * @return
     */
    @Override
    public Map<String, Long> getLatelyTrack(Long userId) {
        HashMap<String, Long> stringLongHashMap = new HashMap<>();
        stringLongHashMap.put("trackId", 394L);
        stringLongHashMap.put("albumId", 36312L);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (userListenProcess != null){
            stringLongHashMap.put("trackId", userListenProcess.getTrackId());
            stringLongHashMap.put("albumId", userListenProcess.getAlbumId());
            return stringLongHashMap;
        }
        return stringLongHashMap;
    }
}
